package boc.sx.gateway.socket.server.handler;

import boc.sx.gateway.convertor.IBaseConvertor;
import boc.sx.gateway.convertor.JsonToXmlConvertor;
import boc.sx.gateway.convertor.XmlToJsonConvertor;
import boc.sx.gateway.core.RequestRoute;
import boc.sx.gateway.service.BusinessHandler;
import boc.sx.gateway.socket.server.SimpleServer;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandlerInvoker;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;

import java.nio.charset.StandardCharsets;

public class SimpleServerHandler extends SimpleChannelInboundHandler<String> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
        // 获取数据
        IBaseConvertor convertToJson = new XmlToJsonConvertor();
        String json = convertToJson.convert((String) msg);
        JSONObject message = JSON.parseObject(json);
        // 检查数据的格式
        String serverCode = message.getJSONObject("SYS_HEAD").getString("SRVC_CD")+"-"
                +message.getJSONObject("SYS_HEAD").getString("SRVC_SCNS");
        // 发送前数据业务处理

        // 发送数据
        Object o = RequestRoute.sendMessageToTargetServer(message, serverCode);

        // 发送数据
        IBaseConvertor convertToXml = new JsonToXmlConvertor();
        byte[] bytes = convertToXml.convert((String)o).getBytes(StandardCharsets.UTF_8);

        ctx.writeAndFlush(convertToXml.convert((String)o));
        int i = SimpleServer.connect.incrementAndGet();
        System.out.println("先用连接数"+ i);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        ctx.close();
    }
}
